

// $("#payment").click(function () {
//     if (checkbox.checked) {
//         alert('已经勾选协议')
//         console.log('已经勾选协议');
//     } else {
//         alert('请勾选协议')
//         console.log('请勾选协议');
//     }
// })
var closeAble = false;
let orderId = '';
var timer;
$(function () {

    orderId = storage.getItem('orderId')

    chaxun()//查询
    fetchInit()//初始化
    // 获取当前页面链接 让手表页返回支付页
    let urls = window.location.href
    // console.log(urls);
    storage.setItem('urls', urls)
    // 如果是1就证明点击过立即领取

    document.addEventListener("visibilitychange", function () {
        let hiddent = document.hidden;
        if (!hiddent) {
            window.location.reload()
        }
    });
    // 获取用户手机号

    $('#phone-input').on('input', function () {
        var phoneNumber = $(this).val();
        console.log(phoneNumber);
        var reg = /^1[3-9]\d{9}$/;
        if (reg.test(phoneNumber)) {

            storage.setItem('phoneNumber', phoneNumber)

            if (storage.getItem('ureId')) {

            } else {

                long()
            }

        } else {
            // toast('请输入正确手机号');
            // 可以在这里添加其他逻辑，比如显示一个错误的提示信息
        }


    });
    // 监控用户有没有勾选协议
    let checkbox = document.getElementById('check');
    $(function () {
        console.log("初始化");
    })
    // $("#check").click(function () {
    //     console.log(checkbox.checked);
    //     if (checkbox.checked) {
    //         console.log('已经勾选协议')
    //     } else {
    //         // alert('请勾选协议')
    //         console.log('请勾选协议');
    //     }
    // })

    // 点击去到推啊变现链接
    $('.modal-contentbx').click(function () {
        window.location.href = 'https://rmdgy-1312109307.cos.ap-guangzhou.myqcloud.com/si.html?appKey=2icgJNgMogVYusjegVpJLDxw3gE4&adslotId=449995'
    })
    // 点击关闭变现弹窗
    $('.chahaobx').click(function () {
        $('.modalbx').hide()
    })
    // 点击关闭第一个弹窗跳出第二弹窗
    $('.chahao').click(function () {
        $('#modal').hide()
        $('#modala').show()
    })
    // 第二个弹窗关闭按钮
    $('.chahaoa').click(function () {
        // $('#modal').hide()
        $('#modala').hide()
        // $('.modalbx').show()
    })
    // 点击活动规则里的确认领取
    $('.ljlq-button').click(function () {
        if (storage.getItem('tj') == 1) {
            // two()
            createOrder(storage.getItem('price'))

        } else {
            createOrder(storage.getItem('price'))

        }

    })
    $('.ljlq,.modal-content').click(function () {
        console.log(111);
        if (storage.getItem("tanc") == '2') {
            var tcjine = storage.getItem('price') - 5 //让第一个弹窗显示的价格减5元
            if (Number.isInteger(tcjine)) {
                console.log(tcjine, 'hhhhhh');
                createOrder(tcjine + 0.2)
                // $('.youhj-je').text(tcjine + 0.2)

            } else {
                // $('.youhj-je').text(tcjine)
                console.log(tcjine);
                createOrder(tcjine)
            }
        } else {
            storage.setItem("tanc", '1')
            // console.log('111');
            OrderDelete()  //先删除订单 然后调起支付
        }
    })
    // 49的不回传最低价38.9
    $('.ljlq4,.modal-contentd').click(function () {
        if (storage.getItem("tanc") == '2') {
            var tcjineb = storage.getItem('price') - 10  //让第二个弹窗显示的价格减5元
            if (Number.isInteger(tcjineb)) {
                createOrder(tcjineb + 0.2)
            } else {
                createOrder(tcjineb)
            }
        } else {
            storage.setItem("tanc", '1')
            OrderDeleteb()  //先删除订单 然后调起支付
        }
    })
    //点击图片拉起支付
    $('.tpzf').click(function () {

        if (storage.getItem('tj') == 1) {
            // two()
            createOrder(storage.getItem('price'))
        } else {
            createOrder(storage.getItem('price'))

        }
        // createOrder()

    })


    var retain = function () {
        var orderId = storage.getItem('orderId')
        if (!closeAble && !orderId) {
            _showlimitedTimeReward()
        } else {
            window.history.back()
        }
    }
    setTimeout(function () {
        window.removeEventListener("popstate", retain, !1)
        window.addEventListener("popstate", retain, !1)
    }, 200)

    // 关闭按钮
    $('#goodsContainer').find('.close').on('click', function () {
        $('#goodsContainer').hide()
    })
    $('#xiadan').click(function () {
        console.log(111);
        if (storage.getItem('phoneNumber') || storage.getItem('ureId')) {

            if (checkbox.checked) {
                // console.log('已经勾选协议')
                // createOrder(storage.getItem('price'))
                if (storage.getItem('payType') == 21) {

                    pinG(storage.getItem('price'))
                } else {
                    createOrder(storage.getItem('price'))
                }
            } else {
                toast('请勾选下方协议')
                // // alert('请勾选协议')
                // console.log('请勾选协议');
            }



        } else {
            toast('请输入正确手机号')
        }

    })

})
storage.setItem('sourceId', 1)   // 设置sourceId
// 业务相关参数
var requestUrl = 'https://kor.l1u.cn',
    // var requestUrl = 'https://h5.comkkf.com',
    price = 0,
    isRetain = 0,
    discountPrice = 0,
    jumpType = 0,
    aliType = 0,
    wxType = 0,
    payType = 1,
    waitTime = 30;

// UI 相关参数
var isSubmit = false,
    checking = false,
    showlimitedTimeRewardTimeout = null,
    countdownnumber = 60.0;

// 走查询
var chaxun = function () {
    // alert(storage.getItem("tj"))

    if (storage.getItem("tj") == 1) {
        // storage.setItem("tj", 2)
        _checkIsPayed()
    }
}
// 两秒后的查询

// 检查是否支付下单
var _checkIsPayed = function () {
    // alert('走查询了')

    var orderId = storage.getItem('orderId')
    if (orderId) {
        console.log(orderId);
        $('.modal-cx').show()
        // 点击已付款
        $('#payfinish ,#unpay').click(function () {
            $('#payfinish').html('查询中...')
            storage.removeItem('tj');
            // alert('准备走接口')
            // clearInterval(timer);

            setTimeout(function () {
                console.log('111');
                $.ajax({
                    type: 'POST',
                    url: requestUrl + '/api/order-phone/checkOrder?orderNo=' + orderId,
                    success: function (res) {
                        if (res.data) {
                            $('.modal-cx').hide() //关闭弹窗
                            window.location.href = '../success/index.html'
                        } else {
                            $('.modal-cx').hide() //关闭弹窗
                            $('#modal').show() //打开优惠弹窗
                            // clearInterval(timer)
                            // createOrder()
                            // history.back()
                        }
                    },
                    error: function () {
                        toast('接口请求失败，请稍后重试')
                    },
                    complete: function () {
                        // $('#payfinish').html('已完成')
                    }
                })
            }, 2000);

            // clearInterval(timer);

        })
    }
}
// 删除上一笔订单
// 第一个弹窗
var OrderDelete = function () {
    if (storage.getItem("tanc") == '1') {
        storage.setItem("tanc", '2')
        $.ajax({
            type: 'get',
            dataType: 'json',
            url: requestUrl + '/api/aliPayConfig/delCache?userId=' + storage.getItem("ureId"),
            contentType: "application/json; charset=utf-8",
            success: function (res) {
                console.log(res);
                var tcjine = storage.getItem('price') - 5 //让第一个弹窗显示的价格减5元
                if (Number.isInteger(tcjine)) {
                    console.log(tcjine);
                    createOrder(tcjine + 0.2)
                } else {
                    console.log(tcjine);
                    createOrder(tcjine)
                }

            }
        })
    } else {
        // storage.setItem("tanc", '2')
        createOrder(storage.getItem('price'))
    }

}
// 第二个弹窗
var OrderDeleteb = function () {
    if (storage.getItem("tanc") == '1') {
        storage.setItem("tanc", '2')
        $.ajax({
            type: 'get',
            dataType: 'json',
            url: requestUrl + '/api/aliPayConfig/delCache?userId=' + storage.getItem("ureId"),
            contentType: "application/json; charset=utf-8",
            success: function (res) {
                console.log(res);
                var tcjineb = storage.getItem('price') - 10 //让第一个弹窗显示的价格减5元
                if (Number.isInteger(tcjineb)) {
                    createOrder(tcjineb + 0.2)
                } else {
                    createOrder(tcjineb)
                }

            }
        })
    } else {
        // storage.setItem("tanc", '2')
        createOrder(storage.getItem('price'))
    }

}


// 初始化
var fetchInit = function (callback) {


    // 获取推啊参数
    var code = getQueryVariable('code')
    // console.log(code);
    var a_oId = getQueryVariable('tkid') || getQueryVariable('a_oId') || getQueryVariable('callback') || getQueryVariable('bxm_id') || getQueryVariable('jcid') || getQueryVariable('callback_url') || getQueryVariable('bc_tag') || getQueryVariable('utm_click') || getQueryVariable('track_id') || getQueryVariable('landingid') || getQueryVariable('dm_id') || getQueryVariable('qcjParamStr') || getQueryVariable('click_id') || getQueryVariable('sz_rli') || getQueryVariable('r_id') || getQueryVariable('nadkey') || getQueryVariable('userkey')
    a_oId = getQueryVariable('callback_url') ? UrlDecode(a_oId) : a_oId
    storage.setItem('code', code)
    storage.setItem('a_oId', a_oId)
    console.log(a_oId);
    var phone = getQueryVariable('phone')
    console.log(phone, '拿到了');
    if (phone) {
        console.log('进到if判断了');
        phoneNumber = Base64.decode(decodeURIComponent(phone))
        console.log(phoneNumber, '解码了');
        storage.setItem('phoneNumber', phoneNumber)
        console.log(storage.getItem('phoneNumber'), '存本地了');
        // $('#phoneNumber').html(phoneNumber)
        // $('#phoneNumber').val(phoneNumber)
        // $('#agreement').prop("checked", true)
    }

    document.addEventListener("visibilitychange", function () {
        let hiddent = document.hidden;
        if (!hiddent) {
            window.location.reload()
        }
    });
    //下边这段代码是为了判断是推啊推广的还是xmob的 如果mt是空 那就是推啊 不为空是xmob 在付款成功页判断变现链接放哪个

    mt = getQueryVariable('userkey')
    console.log(mt);
    if (mt == '') {
        storage.setItem('mtbx', 1)
        // console.log('1');
    } else {
        storage.setItem('mtbx', 2)
        // console.log('2');
    }

    var formPrice = storage.getItem('price')
    $('.formPrice').html(formPrice)
    // 初始化请求页面信息

    // 回显手机号
    $('#phone-input').val(storage.getItem('phoneNumber'))
    $.ajax({
        // url: requestUrl + '/api/link/getLinkInfo?linkPath=' + code,
        // url: requestUrl + '/api/link/getLinkInfo?linkPath=' + code,
        // url: 'https://api.qwmbox.cn/dj/caLink?linkPath=' + code,
        url: requestUrl + '/api/link/getLinkInfo?linkPath=' + code + '&aoId=' + a_oId,
        success: function (res) {
            // var randomNumber = (Math.random() * 3).toFixed(1)
            if (res.data) {
                autoPay = res.data.autoPay  //是否自动拉起
                storage.setItem('autoPay', autoPay)
                gzh = res.data.gzh
                storage.setItem('gzh', gzh)
                console.log(res.data.ad);
                advurl = res.data.advurl
                storage.setItem('advurl', advurl)
                ad = res.data.ad
                storage.setItem('ad', ad)
                caId = res.data.caId
                storage.setItem('caId', caId)
                id = res.data.id
                storage.setItem('id', id)
                jumpType = res.data.jumpType
                storage.setItem('jumpType', jumpType)
                jumpUrl = res.data.jumpUrl
                storage.setItem('jumpUrl', jumpUrl)
                payId = res.data.payId
                storage.setItem('payId', payId)
                payType = res.data.payType
                storage.setItem('payType', payType)
                price = parseFloat(res.data.price)
                // pricea = parseFloat(res.data.price)
                // var randomNumbera = parseFloat(randomNumber)
                // var price = (pricea - randomNumbera).toFixed(1)
                storage.setItem('price', price)
                listId = res.data.listId
                storage.setItem('listId', listId) //如果是1就是权益卡
                $('.jine').html(price)
                $('.hdje').html(price)


                var tcjine = storage.getItem('price') - 5 //让第一个弹窗显示的价格减5元
                if (Number.isInteger(tcjine)) {
                    console.log(tcjine, '整数1');
                    $('.tcjea').html((tcjine - 0.2).toFixed(1))
                } else {
                    console.log(tcjine, '原始1');
                    $('.tcjea').html((tcjine.toFixed(1)))
                }

                var tcjineb = storage.getItem('price') - 10  //让第二个弹窗显示的价格减5元
                if (Number.isInteger(tcjineb)) {
                    console.log(tcjineb, '整数2');
                    $('.tcjeb').html((tcjineb + 0.2).toFixed(1))
                    console.log(tcjineb - 0.2, '第二个');
                } else {
                    console.log(tcjineb, '原始2');
                    $('.tcjeb').html((tcjineb).toFixed(1))
                }

                // 初始化接口传过来的公司名称
                $('.gsmc').html(res.data.company)
                $('.banh').html(res.data.icp)
                $('.tel').html(res.data.tel)

                // 初始化传过来的公众号名称
                $('.gzhname').html(res.data.gzh)


                // if (storage.getItem('ureId')) {
                //     if (storage.getItem('tj') == 1) {

                //         // two()                         //打开就能第二次进入到这个页面后拉起第二次下单的接口
                //         // $('#modal').show()
                //     } else if (storage.getItem('autoPay') == 1) {

                //         createOrder(price)  //打开就能直接拉起支付

                //         // $('#modal').show()

                //     } else {

                //     }
                // } else {
                //     long()
                // }
                if (storage.getItem('price') > 30) {
                    $('.redPacket').html('188')
                } else {
                    $('.redPacket').html('88')
                }
            } else {
                // 用来判断变现猫问题code
                storage.setItem('bxm', 1)
                // toast('服务器繁忙请稍后再试')
                // return false
            }

        },

    })
}

$('input[type=radio][name=payType]').change(function () {
    storage.setItem('payType', this.value)
});


// 登录接口
var long = function () {

    var long = {
        mobile: storage.getItem('phoneNumber'),
        caId: storage.getItem('caId'),
        caLinkId: storage.getItem('id'),
        aoId: storage.getItem('a_oId'),
        murmur: storage.getItem('murmur')
    }

    $.ajax({
        type: 'POST',
        dataType: 'json',
        data: JSON.stringify(long),
        url: requestUrl + '/api/userClient/login',
        contentType: "application/json; charset=utf-8",
        success: function (res) {
            if (res.code == 200) {
                console.log(res);
                let ureId = res.data
                // 用户Id
                storage.setItem('ureId', ureId)


            } else {
                toast('注册/登录失败，请稍后重试')
            }
        },
        error: function () {
            toast('接口请求失败，请重试')
        },
        complete: function () {
            isSubmit = false
        }
    })
}


// 判断微信内置浏览器
var isWeiXin = false
var ua = window.navigator.userAgent.toLowerCase();
if (ua.match(/MicroMessenger/i) == 'micromessenger') {
    isWeiXin = true
} else {
    isWeiXin = false
}
//下单
var createOrder = function (price) {
    storage.setItem('tj', 1)
    // console.log(payType)
    var orderJson = {
        listId: Number(storage.getItem('listId')),
        payType: storage.getItem('payType'),
        price: price,
        payPrice: price,
        // mobile: storage.getItem("ureId"),
        mobile: storage.getItem('phoneNumber'),
        wxInside: isWeiXin ? 1 : 0,
        orderType: storage.getItem('listId'),
        caId: storage.getItem('caId'),
        caLinkId: storage.getItem('id'),
        aoId: storage.getItem('a_oId'),
        murmur: storage.getItem('murmur')
    }
    if (storage.getItem('payType') == 23) {
        let arr = encodeURIComponent(JSON.stringify(orderJson))
        window.location.href = "alipays://platformapi/startapp?appId=20000067&url=https://gq.rew6.cn/wannengye/huafeiyukoukuan.html?data=" + arr;
    } else {
        $.ajax({
            type: 'POST',
            dataType: 'json',
            data: JSON.stringify(orderJson),
            // url: 'https://ddj.qwmbox.cn/api/aliPayConfig/aliPay',
            url: requestUrl + '/api/aliPayConfig/aliPay',
            // url: requestUrl + '/api/aliPayConfig/aliPayV2',
            contentType: "application/json; charset=utf-8",
            success: function (res) {
                // console.log(res, '222222222222222222');
                // $('#loader').hide();
                // console.log(res, '下单返回数据');
                var orderId = res.data.orderId
                storage.setItem('orderId', orderId)
                if (res.data.wxDomain) {
                    window.location.href = res.data.wxDomain + '?mwebUrl=' + encodeURIComponent(res.data.mwebUrl) + '&mwebForm' + encodeURIComponent(res.data.mwebForm)
                    return false
                }
                // 微信内外
                if (res.data.mwebUrl) {
                    // var urlss = encodeURIComponent(storage.getItem('urls'))
                    // console.log(urlss);
                    // console.log(res.data.mwebUrl + '&redirect_url=' + urlss);
                    // window.location.assign(res.data.mwebUrl);
                    // window.location.assign(`${res.data.mwebUrl}&redirect_url=${encodeURIComponent(window.location.origin + `${storage.getItem('urls')}`)}`);

                    // window.location.assign(res.data.mwebUrl)

                    // $('body').append(res.data.mwebUrl)
                    // window.location.href = res.data.mwebUrl
                    if (storage.getItem('payType') == 1) {
                        setTimeout(function () {
                            _checkIsPayed()
                        }, 800)
                    }
                    location.replace(res.data.mwebUrl)
                    return false
                }
                // 支付宝
                if (res.data.mwebForm) {
                    $('body').append(res.data.mwebForm)
                    return false
                }
            },
            error: function () {
                // $('#loader').hide();
                toast('接口请求失败，请重试')
            }
        })
    }
}
var pinG = function (price) {
    storage.setItem('tj', 1)
    $.ajax({
        type: 'POST',
        dataType: 'json',
        data: JSON.stringify({
            listId: Number(storage.getItem('listId')),
            payType: storage.getItem('payType'),
            price: price,
            payPrice: price,
            mobile: storage.getItem('phoneNumber'),
            wxInside: isWeiXin ? 1 : 0,
            orderType: storage.getItem('listId'),
            caId: storage.getItem('caId'),
            caLinkId: storage.getItem('id'),
            aoId: storage.getItem('a_oId'),
            murmur: storage.getItem('murmur')
        }),
        // url: 'http://vqh98j.natappfree.cc/api/aliPayConfig/aliPay',
        url: requestUrl + '/api/aliPayConfig/aliPay',
        contentType: "application/json; charset=utf-8",
        success: function (res) {
            console.log(res, '请求成功');
            let data = JSON.parse(res.data)
            var orderNo = data.order_no;
            storage.setItem('orderId', orderNo)
            pingpp.createPayment(data, function (result, err) {
                if (result == "success") {

                    window.location.href = '../success/index.html'
                    // 只有微信公众账号 (wx_pub)、微信小程序 (wx_lite)、QQ 公众号 (qpay_pub)、支付宝口碑 (alipay_qr)
                    // 支付成功的结果会在这里返回，其他的支付结果都会跳转到 extra 中对应的 URL。
                } else if (result == "fail") {
                    // data 不正确或者微信公众账号/微信小程序/QQ 公众号/支付宝口碑支付失败时会在此处返回
                } else if (result == "cancel") {
                    // 微信公众账号、微信小程序、QQ 公众号、支付宝口碑支付取消支付
                }
            });
        },
        fail: function (err) {
            console.log(err, '请求失败');
        }
    })
}

// 第二次下单访问的接口
var two = function () {
    if (storage.getItem('orderId')) {
        $.ajax({
            type: 'get',
            dataType: 'json',
            url: requestUrl + '/api/aliPayConfig/linkOrderPay?orderNo=' + storage.getItem('orderId'),
            contentType: "application/json; charset=utf-8",
            success: function (res) {
                // console.log('第二次接口调用成功');

                if (res.data.mwebUrl) {
                    window.location.href = res.data.mwebUrl
                } else {
                    createOrder(storage.getItem('price'))
                }
            }
        })
    } else {
        // console.log('调用了第二个接口但是订单号未空');
        createOrder(storage.getItem('price'))
    }
}



var countDown = function () {
    if (countdownnumber > 0) {
        countdownnumber = countdownnumber - 0.1
        $('#countDown').html(countdownnumber.toFixed(1))
        setTimeout(countDown, 100)
    } else {
        $('#popContainer').hide()
        var price = storage.getItem('servicePrice')
        storage.setItem('price', price)
        storage.setItem('isRetain', 0)
    }
}
var toast = function (msg, time) {
    // 1. 创建要添加的 DOM 元素
    const toast = document.createElement('div');
    toast.className = 'am-toast am-toast-mask';
    toast.innerHTML = '<span><span class="am-toast-notice-content">' + msg + '</span></span>';

    // 2. 添加元素到 body 标签中
    document.body.appendChild(toast);

    setTimeout(function () {
        $(".am-toast").fadeOut()
    }, time ? time : 1500)
}

//获取url参数
var getQueryVariable = function (variable) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] == variable) { return pair[1]; }
    }
    return ('');
}

var isIOS = function () {
    var u = navigator.userAgent;
    var isAndroid = u.indexOf("Android") > -1 || u.indexOf("Adr") > -1; //android终端
    var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
    if (isAndroid) {
        return "android";
    }
    if (isiOS) {
        return "ios";
    }
    return false;
}

// url解码
var UrlDecode = function (zipStr) {
    var uzipStr = '';
    for (var i = 0; i < zipStr.length; i += 1) {
        var chr = zipStr.charAt(i);
        if (chr === '+') {
            uzipStr += ' ';
        } else if (chr === '%') {
            var asc = zipStr.substring(i + 1, i + 3);
            if (parseInt('0x' + asc) > 0x7f) {
                uzipStr += decodeURI('%' + asc.toString() + zipStr.substring(i + 3, i + 9).toString());
                i += 8;
            } else {
                uzipStr += AsciiToString(parseInt('0x' + asc));
                i += 2;
            }
        } else {
            uzipStr += chr;
        }
    }

    return uzipStr;
}

var StringToAscii = function (str) {
    return str.charCodeAt(0).toString(16);
}

var AsciiToString = function (asccode) {
    return String.fromCharCode(asccode);
}

// 所有弹窗绑定关闭按钮
$('#popContainer').find('.close').on('click', function () {
    $('#popContainer').hide()
    var price = storage.getItem('servicePrice')
    storage.setItem('price', price)
    storage.setItem('isRetain', 0)
})

$('.pop-mask').click(function () {
    if ($(this).parent().attr('id') == 'popContainer') {
        $('#popContainer').hide()
    } else {
        $(this).parent().hide()
    }
})

$('#customerService').click(function () {
    $('#customerServiceContainer').show()
    $('#customerServiceContainer').find('.close').on('click', function () {
        $('#customerServiceContainer').hide()
    })
})

var winHeight = $(window).height();
// console.log(winHeight);
$(window).resize(function () {
    var thisHeight = $(this).height();
    if (winHeight - thisHeight > 50) {
        //软键盘弹出
        $('.diog-content').css({ 'top': '-160px', 'position': "absolute" });
    }
})
// 获取用户唯一参数
const fingerprint = Fingerprint2.get((components) => {
    const values = components.map(component => component.value);
    murmur = Fingerprint2.x64hash128(values.join(''), 31);
    // console.log(murmur, '111111111111111111111111');
    storage.setItem('murmur', murmur)
});